﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace FT
{
    /// <summary>
    /// 执行ffmpeg的命令行
    /// </summary>
    public class FTCommander
    {
        public delegate void OnDataReceived(string data);
        public static event OnDataReceived OnDataReceivedHandler;

        private static bool isRunning = false;

        public static void Execute(string command)
        {
            if (isRunning)
            {
                return;
            }

            new Thread(() =>
            {
                isRunning = true;
                Thread.CurrentThread.IsBackground = true;
                command = "/c chcp 437&&" + command.Trim().TrimEnd('&') + "&exit";

                Process process = new Process();
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = command;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;

                process.OutputDataReceived += (sender, e) =>
                {
                    OnDataReceivedHandler?.Invoke(e.Data);
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    OnDataReceivedHandler?.Invoke(e.Data);
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();
                process.Close();

                isRunning = false;

                OnDataReceivedHandler("Complete");

            }).Start();
        }
    }
}